package com.alexsun.smarthome

import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.view.Surface
import android.view.TextureView
import android.view.TextureView.SurfaceTextureListener
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity


class VideoActivity : AppCompatActivity() {
    var player: MediaPlayer? = null
    var ttv: TextureView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video)
        player = MediaPlayer()
        player!!.setVolume(0f, 0f)
        ttv = findViewById<View>(R.id.text_screen) as TextureView
        ttv!!.visibility = View.VISIBLE
        ttv!!.surfaceTextureListener = TextureListen()
        try {
            val streamUrl = "http://192.168.1.105:8089/flv?app=live&stream=test"
            player!!.setDataSource(this, Uri.parse(streamUrl))
            player!!.prepare()
            player!!.setOnPreparedListener {
                player!!.start()
                player!!.isLooping = true
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        val btnImage: Button = findViewById<View>(R.id.button) as Button
        btnImage.setOnClickListener {
            val img: ImageView = findViewById<View>(R.id.image_screen) as ImageView
            img.setImageBitmap(ttv!!.bitmap)
        }
    }

    inner class TextureListen : SurfaceTextureListener {
        override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, i: Int, i1: Int) {
            try {
                player!!.setSurface(Surface(surfaceTexture))
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        override fun onSurfaceTextureSizeChanged(surfaceTexture: SurfaceTexture, i: Int, i1: Int) {}
        override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean {
            return false
        }

        override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {}
    }
}